#include "imglib/winimage.h"

namespace img {

void BlendImage(HDC hDC, int xd, int yd, int wd, int hd, int xs, int ys, int ws, int hs, const image< BGRA<unsigned char> > & src, unsigned char alpha)
{
	BLENDFUNCTION blend;
	blend.BlendOp = AC_SRC_OVER;
	blend.BlendFlags = 0;
	blend.SourceConstantAlpha = alpha;
	blend.AlphaFormat = 0;

	HDC tmpDC = CreateCompatibleDC(hDC);
	HBITMAP tmpBmp = CreateCompatibleBitmap(hDC, ws, hs);
	HGDIOBJ oldBmp = SelectObject(tmpDC, tmpBmp);

	DrawImage(tmpDC, 0, 0, ws, hs, xs, ys, src);
	AlphaBlend(hDC, xd, yd, wd, hd, tmpDC, 0, 0, ws, hs, blend);

	SelectObject(tmpDC, oldBmp);
	DeleteObject(tmpBmp);
	DeleteDC(tmpDC);
}

void BlendImage(HDC hDC, int xd, int yd, int wd, int hd, int xs, int ys, int ws, int hs, const image< BGRA<unsigned char> > & src)
{
	BLENDFUNCTION blend;
	blend.BlendOp = AC_SRC_OVER;
	blend.BlendFlags = 0;
	blend.SourceConstantAlpha = 0xFF;
	blend.AlphaFormat = 1;

	int w = src.width();
	int h = src.height();

	BITMAPINFO info;
	BITMAPINFOHEADER & header = info.bmiHeader;
	ys = h - hs - ys;
	if (src.order() == top_down)
		h = - h;
	memset(&header, 0, sizeof(BITMAPINFOHEADER));
	header.biSize			= sizeof(BITMAPINFOHEADER); 
	header.biWidth			= w; 
	header.biHeight			= h;
	header.biPlanes			= 1; 
	header.biBitCount		= 32; 
	header.biCompression	= BI_RGB; 

	HDC tmpDC = CreateCompatibleDC(hDC);
	void * pBits;
	HBITMAP tmpBmp = CreateDIBSection(0, &info, DIB_RGB_COLORS, &pBits, 0, 0);
	HGDIOBJ oldBmp = SelectObject(tmpDC, tmpBmp);
	memcpy(pBits, src.data(), src.bytes());
	AlphaBlend(hDC, xd, yd, wd, hd, tmpDC, 0, 0, ws, hs, blend);

	SelectObject(tmpDC, oldBmp);
	DeleteObject(tmpBmp);
	DeleteDC(tmpDC);
}


} // img
